<template>
  <lay-table :page="page" :columns="columns" :data-source="roleList" :loading="loading"
    v-model:selected-keys="selectedKeys" style="height: 100%;">
    <template v-slot:toolbar>
      <lay-button size="xs" type="primary" @click="changeAddVisible">新增</lay-button>
    </template>
    <template #status="{ row }">
      <lay-switch v-model="row.status" @change="changeStatus($event, row)" onswitch-text="启用"
        unswitch-text="禁用"></lay-switch>
    </template>
    <template v-slot:operator="{ row }">
      <lay-button size="xs" @click="update(row)" border="green" border-style="dashed">编辑</lay-button>
      <lay-popconfirm :content="row.user_count === 0 ? '确定要删除吗？' : '不能删除！存在已关联用户!'" position="left"
        @confirm="remove(row)" @cancel="() => layer.msg('操作已取消！', { icon: 3, time: 1000 })">
        <lay-button size="xs" border="red" border-style="dashed" :disabled="row.user_count !== 0">删除</lay-button>
      </lay-popconfirm>
    </template>
  </lay-table>

  <!-- 新增 ========================================== -->
  <lay-layer v-model="addVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'新增角色'" :btn="addAction">
    <div style="padding: 20px;">
      <lay-form :model="newRole" ref="addRoleForm">
        <lay-form-item label="名称" prop="name" required>
          <lay-input v-model="newRole.name"></lay-input>
        </lay-form-item>
        <lay-form-item label="代码" prop="code" required>
          <lay-input v-model="newRole.code"></lay-input>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>

  <!-- 修改信息 ========================================== -->
  <lay-layer v-model="updateVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'修改角色'"
    :btn="updateAction">
    <div style="padding: 20px;">
      <lay-form :model="updateRole" ref="updateRoleForm">
        <lay-form-item label="ID" prop="id">
          <lay-input v-model="updateRole.id" :disabled="true"></lay-input>
        </lay-form-item>
        <lay-form-item label="名称" prop="name" required>
          <lay-input v-model="updateRole.name"></lay-input>
        </lay-form-item>
        <lay-form-item label="代码" prop="code">
          <lay-input v-model="updateRole.code"></lay-input>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue';
import { layer } from '@layui/layui-vue';
import api from '@/api';

const loading = ref(true);
const selectedKeys = ref([]);

const page = reactive({ current: 1, limit: 20, limits: [20, 50, 100, 500], total: 10, layout: ["page", "limits", "prev", "refresh", "count", "next", "skip",] });
// 分页、排序、筛选等参数
const change = (page) => {
  // queryForm.value.pageNum = page.current;
  // queryForm.value.pageSize = page.limit;
  // loading.value = true;
  // initDataList();
}
// attach change handler to page prop per layui-vue new API
page.change = change;

// 获取角色列表
const roleList = ref([]);
async function getRoleList() {
  try {
    let response = await api.get('/system/role/list');
    roleList.value = response.data;
    page.total = response.data.length
    loading.value = false
  } catch (e) {
    console.error('获取角色列表失败', e);
  }
}


// 新增角色
const addVisible = ref(false);
const changeAddVisible = () => {
  addVisible.value = !addVisible.value;
}
const newRole = reactive({
  name: "普通用户",
  code: "user",
})
const addRoleForm = ref();

const addRoleHandler = async () => {
  let response = await api.get('/system/role/add', { name: newRole.name, code: newRole.code }
  );

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    getRoleList(); // 刷新角色列表
    addVisible.value = !addVisible.value;
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const addAction = ref([
  {
    text: "添加",
    callback: () => {
      if (addRoleForm.value.validate()) {
        addRoleHandler();
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      addVisible.value = !addVisible.value;
    }
  }
])


// 修改角色
const updateVisible = ref(false);
const updateRole = reactive({
  id: null,
  name: "",
  code: "",
  status: null
})
const updateRoleForm = ref();

async function update(row) {
  console.log('@row:', row.id);
  updateRole.id = row.id;
  updateRole.name = row.name;
  updateRole.code = row.code;
  updateRole.status = row.status;
  updateVisible.value = !updateVisible.value;
}

const updateRoleHandler = async () => {
  let response = await api.get('/system/role/update', {
    id: updateRole.id, name: updateRole.name,
    code: updateRole.code, status: updateRole.status
  });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    getRoleList(); // 刷新角色列表
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const updateAction = ref([
  {
    text: "保存",
    callback: () => {
      if (updateRoleForm.value.validate()) {
        updateRoleHandler().then(() => {
          updateVisible.value = false;
        });

      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      updateVisible.value = !updateVisible.value;
    }
  }
])


// 切换启用状态
const changeStatus = (isChecked, row) => {
  roleList.value.forEach((item) => {
    if (item.id === row.id) {
      console.log(isChecked)
      updateRole.id = item.id;
      updateRole.name = item.name;
      updateRole.code = item.code;
      updateRole.status = isChecked;
      updateRoleHandler();
    }
  })
}


// 删除角色
async function remove(row) {
  console.log('@row:', row.id);
  if (row.user_count !== 0) {
    layer.msg('不能删除！存在已关联用户!', { icon: 2, time: 2000 });
    return;
  }
  const response = await api.get('/system/role/delete', { id: row.id });
  if (response.code === 200) {
    selectedKeys.value = [];
    getRoleList(); // 刷新角色列表
    console.log(`删除角色 ${row.id} 成功！`, response);
    layer.msg(response.msg, { icon: 1, time: 1000 })
  } else {
    layer.msg(response.msg, { icon: 2, time: 1000 })
  }
}


const columns = [
  // { fixed: "left", type: "checkbox", title: "复选" },
  { title: "ID", key: "id", width: "70px", align: 'center', sort: true },
  { title: "名称", key: "name", align: 'center', ellipsisTooltip: true, },
  { title: "代码", key: "code", align: 'center', ellipsisTooltip: true, },
  { title: "关联用户量", key: "user_count", align: 'center', ellipsisTooltip: true, },
  { title: "启用", key: "status", align: 'center', customSlot: "status" },
  { title: "创建时间", key: "create_time", align: 'center', ellipsisTooltip: true, },
  { title: "更新时间", key: "update_time", align: 'center', ellipsisTooltip: true, },
  { title: "备注", key: "remark", align: 'center' },
  { title: "操作", key: "operator", width: "100px", align: 'center', customSlot: "operator", fixed: "right", ignoreExport: true }
]

onMounted(() => {
  getRoleList();
});
</script>

<style scoped>
.layui-card-body {
  padding: 5px !important;
}

.layui-form-onswitch {
  border-color: var(--global-checked-color) !important;
  background-color: var(--global-checked-color) !important;
}
</style>